//
//  BaseCollectionView.m
//  公考神器
//
//  Created by 毕武侠 on 16/3/14.
//  Copyright © 2016年 毕武侠. All rights reserved.
//

#import "BaseCollectionView.h"
#import "BaseCollectionModel.h"
#import "BaseCollectionViewCell.h"
#import "UIScrollView+EmptyDataSet.h"

@interface BaseCollectionView () <UICollectionViewDelegate, UICollectionViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, cellDidActionDelegate>

@property (nonatomic, assign) NSUInteger pageNumber;

@property (nonatomic, getter=isLoading) BOOL loading;

@end

@implementation BaseCollectionView

- (void)initstance {
    self.delegate = self;
    self.dataSource = self;
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
    
    NSLog(@"道题页面");
    
    
    _step = 0;
    
    self.pageNumber = 1;
    self.backgroundColor = [UIColor whiteColor];
}

- (void)setSourceData:(NSMutableArray *)sourceData {
    _sourceData = sourceData;
    [self reloadData];
    
    if (_sourceData.count == 0) {
        if (self.title.length == 0) {
            self.title = @"暂无数据";
        }
        [self reloadEmptyDataSet];
    }
}

- (void)registerCellClass:(NSString *)cellClassName cellIdentifier:(NSString *)identifier {
    self.cellClassName = cellClassName;
    self.identifier = identifier;
    
    [self registerNib:[UINib nibWithNibName:cellClassName bundle:nil] forCellWithReuseIdentifier:identifier];
    
    [self initstance];
}

- (void)initRefreshView {
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNumber = 0;
        [self loadData];
    }];
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mj_footer.automaticallyHidden = YES;
    self.mj_footer.automaticallyChangeAlpha = YES;
}

- (void)refreshView {
    [self reloadData];
    if (_sourceData.count == 0) {
        if (self.title.length == 0) {
            self.title = @"暂无数据";
        }
        [self reloadEmptyDataSet];
    }
}

- (void)setLoading:(BOOL)loading {
    if (self.isLoading == loading) {
        return;
    }
    
    _loading = loading;
    [self reloadEmptyDataSet];
}

- (void)setUrl:(NSString *)url {
    _url = url ? [NSString stringWithFormat:@"%@%@",[OtherNetworking sharedManager].STRURL, url] : [OtherNetworking sharedManager].STRURL;
}

- (NSString *)modelClass {
    if (!_modelClass) {
        _modelClass = @"BaseCollectionModel";
    }
    return _modelClass;
}

- (NSString *)title {
    if (!_title) {
        _title = @"";
    }
    return _title;
}

- (NSString *)message {
    if (!_message) {
        _message = @"";
    }
    return _message;
}

#pragma mark ----------------------- 滚动 ------------------------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{ //全局变量记录滑动前的contentOffset
//    _lastContentOffsetY = scrollView.contentOffset.y;//判断上下滑动时
//    _lastContentOffsetX = scrollView.contentOffset.x;
    //判断左右滑动时
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    _step = scrollView.contentOffset.x /screenWidth ;
    NSLog(@"qqqqq = %f",scrollView.contentOffset.x /screenWidth);
    
//    if (self.block) {
//        self.block(_step);
//    };
    
    NSString *str = [NSString stringWithFormat:@"%ld",_step];
    
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:str,@"name", nil];
    
    
    
    // 2.创建通知

    
    NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];
    
    // 3.通过 通知中心 发送 通知
    
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    

    

    

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    _step = scrollView.contentOffset.x /screenWidth ;
    NSLog(@"aaaaa == %f",scrollView.contentOffset.x /screenWidth);
    
    
    NSString *str = [NSString stringWithFormat:@"%ld",_step];
    
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:str,@"name", nil];
    
    
    
    // 2.创建通知
    
    
    NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];
    
    // 3.通过 通知中心 发送 通知
    
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    

    

}

#pragma mark  collectionView delegate dataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.sourceData.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.minLineSpace;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return self.minInteritemSpace;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return  self.edgeInsets;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    BaseCollectionModel *model = self.sourceData[indexPath.row];
    return  model.cellSize;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:
                                  self.identifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[BaseCollectionViewCell alloc] init];
    }
    
    BaseCollectionModel *model = self.sourceData[indexPath.row];
    
    cell.count          = self.sourceData.count;
    cell.indexPath      = indexPath;
    cell.actionDelegate = self;
    [cell bindModel:model];
    return cell;
}

//帖子的监听方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.didDatagate respondsToSelector:@selector(collectionView:didSelectIndexPath:)]) {
        [self.didDatagate collectionView:self didSelectIndexPath:indexPath];
    }
}

#pragma mark - cell Action

- (void)actionIndexPath:(NSIndexPath *)indexPath infoData:(id)data {
    if ([self.didDatagate respondsToSelector:@selector(collectionView:didActionIndexPath:infoData:)]) {
        [self.didDatagate collectionView:self didActionIndexPath:indexPath infoData:data];
    }
}

#pragma mark - load Data

- (void)loadData {
    if (!self.url || !self.parameter) {
        [self.mj_header endRefreshing];
        return;
    }
    
    [self.mj_footer endRefreshing];
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.body = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 200) {
            NSMutableArray *data = receive.data;
            if ([data count] > 0) {
                self.pageNumber++;
                [self.sourceData removeAllObjects];

                self.sourceData = data;
            }
        }
        [self.mj_header endRefreshing];
    } failure:^(id reslut) {
        [self.mj_header endRefreshing];
    }];
}

- (void)loadMoreData {
    if (!self.parameter) {
        [self.mj_footer endRefreshing];
        return;
    }
    
    if (self.pageNumber <= 1) {
        self.pageNumber++;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.body = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 200) {
            NSMutableArray *data = receive.data;
            if ([data count] > 0) {
                self.pageNumber++;
                [self.sourceData addObjectsFromArray:data];;
                [self reloadData];
                [self.mj_footer endRefreshing];
            } else {
                [self.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            [self.mj_footer endRefreshing];
        }
    } failure:^(id reslut) {
        [self.mj_footer endRefreshing];
    }];
}

- (void)reloadNewData {
    if (!self.parameter) {
        [self.mj_header endRefreshing];
        self.loading = NO;
        if (self.sourceData.count == 0) {
            self.title = @"暂无数据";
            [self reloadEmptyDataSet];
        }
        return;
    }
    
    self.loading = YES;
    
    self.pageNumber = 0;
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.body = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
        self.loading = NO;
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 2000) {
            NSMutableArray *data = receive.data;
            if (data.count > 0) {
                self.pageNumber++;
                
                [self.sourceData removeAllObjects];
                self.sourceData = data;
                [self setContentOffset:CGPointMake(0,0) animated:YES];
            } else {
                if (self.sourceData.count == 0) {
                    self.title = @"暂无数据";
                    [self reloadEmptyDataSet];
                }
            }
        } else {
            if (self.sourceData.count == 0) {
                self.title = @"暂无数据";
                [self reloadEmptyDataSet];
            }
        }
        [self.mj_header endRefreshing];
    } failure:^(id reslut) {
        self.loading = NO;
        [self.mj_header endRefreshing];
        if (self.sourceData.count == 0) {
            self.title = @"哦，您的网络似乎去了火星！";
            [self reloadEmptyDataSet];
        }
    }];
}

#pragma mark - DZNEmptyDataSetSource Methods

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    text = self.title;
    font = [UIFont systemFontOfSize:17.0];
    textColor = [UIColor grayColor];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:self.isLoading ? @"loading_imgBlue" : IMG_EmptyDefault];
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -(self.height / 6);//-(SCREEN_HEIGHT / 6);
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView {
    return 0.0;
}

#pragma mark - DZNEmptyDataSetDelegate Methods

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return self.allowTouchData;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

// YES: 开始转圈
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView {
    return self.isLoading;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

#pragma mark - View Auto-Rotation

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
